import 'dart:io';

import 'package:dio/dio.dart';
import 'package:duo_zui/constant/cache_key.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../router.dart';
import 'package:duo_zui/model/model.dart';

class WriteCommentPage extends StatefulWidget{
  int articleId;

  Post post;

  WriteCommentPage({Key key, this.articleId, this.post}): super(key:key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _writeCommentPageState();
  }
}

class _writeCommentPageState extends State<WriteCommentPage>{
  String _content;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
             title: Text("写评论", style: TextStyle(color: Colors.black38)),
              leading: IconButton(
                icon:Icon(Icons.arrow_back_ios,size:20) ,
                onPressed: (){
                  String url = 'http://www.appshuo.club/appview/p/';
                  MyRouter.push(context, MyRouter.articelPage, {'url': '$url${widget.post.id}', 'article':widget.post});
                },),
             iconTheme: IconThemeData(color: Colors.black38),
                actions: <Widget>[
                  Builder(
                builder: (ctx) {
                    return IconButton(icon: Icon(Icons.send), onPressed: () {
                      String url = 'http://www.appshuo.club/appview/p/';
                      _rourLogin(MyRouter.articelPage,{'url': '$url${widget.post.id}', 'article':widget.post});
                   });
                },)],
    ),
    body: TextField(
      onChanged: (str) {
        _content = str;
        setState(() {});
      },
      decoration: InputDecoration(
          hintText: "说点什么吧～",
          hintStyle: TextStyle(
              color: const Color(0xFF808080)
          ),
          border: OutlineInputBorder(
              borderRadius: const BorderRadius.all(const Radius.circular(10.0))
          )
      ),
      maxLines: 6,
      maxLength: 150,
      //controller: _controller,
    ));
  }

  void getData(key,params)async{
      Dio dio = new Dio();
      Response response = await dio.post('http://www.appshuo.club/api/api/comment/add',
          data:{'articleId':widget.articleId,'content':_content,'parentId':0,'replyCommentId':1},
          options: Options(
              followRedirects: false,
              validateStatus: (status) { return status < 500; }
          ));
      if(response.statusCode != 200){
        return;//如果没有数据就不继续了
      }
      MyRouter.push(context, key, params);
  }

  _rourLogin(key,params) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getBool(CacheKey.USER_IS_LOGIN)?? false){
      getData(key,params);
    }else{
      MyRouter.push(context, MyRouter.loginPage,{'url': MyRouter.articelPage});
    }
  }
}